package com.menghao.rpc.provider.regisiter;

import com.menghao.rpc.exception.InitializationException;
import com.menghao.rpc.provider.model.ProviderKey;
import com.menghao.rpc.util.ProviderHostUtils;
import com.menghao.rpc.zookeeper.CuratorClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.Assert;

import java.text.MessageFormat;

/**
 * <p>服务提供方注册.</br>
 * <p>需要的信息：契约、实现、IP、端口</p>
 *
 * @author MarvelCode
 */

public class ProviderRegister implements ApplicationListener<ContextRefreshedEvent> {

    private CuratorClient curatorClient;

    private Integer port;

    public ProviderRegister(CuratorClient curatorClient, Integer port) {
        this.curatorClient = curatorClient;
        this.port = port;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext currentContext = event.getApplicationContext();
        // 忽略子容器
        if (currentContext.getParent() != null) {
            return;
        }
        ProviderRepository apiRepository = currentContext.getBean(ProviderRepository.class);
        Assert.notNull(apiRepository, "初始化失败");
        String ip = ProviderHostUtils.getLocalHost();
        String nodeValue = ip + ":" + port;
        for (ProviderKey providerKey : apiRepository.getProviders()) {
            String path = getNodePath(providerKey) + "/" + nodeValue;
            try {
                if (!curatorClient.isExisted(path)) {
                    curatorClient.createEphemeralNode(path, null);
                }
            } catch (Exception e) {
                throw new InitializationException(MessageFormat.format("create node: {0} value: {1} excecption", path, nodeValue));
            }
        }
    }

    private String getNodePath(ProviderKey providerKey) {
        return "/" + providerKey.getContract() + ":" + providerKey.getImplCode();
    }
}
